// src/services/api.js (更新课程相关部分)
import axios from 'axios'

// 根据环境自动选择API地址
const API_BASE_URL = process.env.NODE_ENV === 'production' 
  ? 'https://your-production-api.com'
  : 'http://localhost:8000'

console.log('API Base URL:', API_BASE_URL)

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    console.log('发送请求:', config.method?.toUpperCase(), config.url)
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    console.log('收到响应:', response.status, response.config.url)
    return response.data
  },
  error => {
    console.error('响应错误:', error)
    if (error.code === 'ECONNREFUSED') {
      console.error('无法连接到服务器，请确保后端服务正在运行')
    }
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 测试连接函数
export const testConnection = async () => {
  try {
    const response = await apiClient.get('/health')
    console.log('连接测试成功:', response)
    return response
  } catch (error) {
    console.error('连接测试失败:', error)
    throw error
  }
}

// 学员API
export const studentAPI = {
  async getStudents(params = {}) {
    try {
      const response = await apiClient.get('/students/', { params })
      return {
        items: response.items || response || [],
        total: response.total || (response?.length || 0)
      }
    } catch (error) {
      console.error('获取学员列表失败:', error)
      return { items: [], total: 0 }
    }
  },
  
  async getStudent(id) {
    return await apiClient.get(`/students/${id}`)
  },
  
  async createStudent(data) {
    return await apiClient.post('/students/', data)
  },

  async updateStudyHours(id, hours) {
  return await apiClient.patch(`/students/${id}/study-hours?hours=${hours}`)
},
  
  async updateHonors(id, count) {
  return await apiClient.patch(`/students/${id}/honors`, null, {
    params: { count: count }
  })
},
  
  async deleteStudent(id) {
    return await apiClient.delete(`/students/${id}`)
  }
}

// 教师API
export const teacherAPI = {
  async getTeachers(params = {}) {
    try {
      const response = await apiClient.get('/teachers/', { params })
      return {
        items: response.items || response || [],
        total: response.total || (response?.length || 0)
      }
    } catch (error) {
      console.error('获取教师列表失败:', error)
      return { items: [], total: 0 }
    }
  },
  
  async getTeacher(id) {
    return await apiClient.get(`/teachers/get-teacher/${id}`)
  },
  
  async createTeacher(data) {
    return await apiClient.post('/teachers/', data)
  },
  
  async updateTeacher(id, data) {
    return await apiClient.put(`/teachers/${id}`, data)
  },
  
  async deleteTeacher(id) {
    return await apiClient.delete(`/teachers/${id}`)
  }
}

// 课程API (修正版)
export const courseAPI = {
  async getCourses(params = {}) {
    try {
      // 转换分页参数：从 page/page_size 转换为 skip/limit
      const apiParams = {}
      
      if (params.page && params.page_size) {
        apiParams.skip = (params.page - 1) * params.page_size
        apiParams.limit = params.page_size
      } else {
        apiParams.skip = params.skip || 0
        apiParams.limit = params.limit || 50 // 增加limit以获取更多课程
      }
      
      // 其他参数直接传递
      Object.keys(params).forEach(key => {
        if (!['page', 'page_size', 'skip', 'limit'].includes(key)) {
          apiParams[key] = params[key]
        }
      })

      console.log('课程API请求参数:', apiParams)
      const response = await apiClient.get('/courses/', { params: apiParams })
      console.log('课程API响应:', response)
      
      return {
        items: response.items || response || [],
        total: response.total || (response?.length || 0)
      }
    } catch (error) {
      console.error('获取课程列表失败:', error)
      return { items: [], total: 0 }
    }
  },
  
  async getCourse(id) {
    return await apiClient.get(`/courses/${id}`)
  },
  
  async createCourse(data) {
    return await apiClient.post('/courses/', data)
  },
  
  async updateCourse(id, data) {
    return await apiClient.put(`/courses/${id}`, data)
  },
  
  async deleteCourse(id) {
    return await apiClient.delete(`/courses/${id}`)
  },
  
  async getSubCourses(parentId) {
    return await apiClient.get(`/courses/${parentId}/sub-courses/`)
  },
  
  async getCourseStatistics() {
    return await apiClient.get('/courses/statistics/')
  }
}

// 荣誉管理API
export const honorAPI = {
  async getHonors(params = {}) {
    try {
      // 转换分页参数：从 page/page_size 转换为 skip/limit
      const apiParams = {}

      if (params.page && params.page_size) {
        apiParams.skip = (params.page - 1) * params.page_size
        apiParams.limit = params.page_size
      } else {
        apiParams.skip = params.skip || 0
        apiParams.limit = params.limit || 50
      }

      // 其他参数直接传递
      Object.keys(params).forEach(key => {
        if (!['page', 'page_size', 'skip', 'limit'].includes(key)) {
          apiParams[key] = params[key]
        }
      })

      console.log('荣誉API请求参数:', apiParams)
      const response = await apiClient.get('/honors/', { params: apiParams })
      console.log('荣誉API响应:', response)

      return {
        items: response.items || response || [],
        total: response.total || (response?.length || 0)
      }
    } catch (error) {
      console.error('获取荣誉列表失败:', error)
      return { items: [], total: 0 }
    }
  },
  async getHonor(id) {
    return await apiClient.get(`/honors/${id}`)
  },
  async createHonor(data) {
    return await apiClient.post('/honors', data)
  },
  async updateHonor(id, data) {
    return await apiClient.put(`/honors/${id}`, data)
  },
  async deleteHonor(id) {
    return await apiClient.delete(`/honors/${id}`)
  },
  async getHonorStatistics() {
    try {
      const response = await apiClient.get('/honors/statistics')
      return response || {}
    } catch (error) {
      console.error('获取荣誉统计信息失败:', error)
      return {}
    }
  },
  // 获取某个学生的荣誉记录（辅助查询）
  async getStudentHonors(studentId, params = {}) {
    try {
      const response = await apiClient.get(`/students/${studentId}/honors`, { params })
      return {
        items: response.items || response || [],
        total: response.total || (response?.length || 0)
      }
    } catch (error) {
      console.error('获取学生荣誉失败:', error)
      return { items: [], total: 0 }
    }
  }
}

// 报名管理API 
export const signupAPI = {
  // 报名相关接口
  async getSignups(params = {}) {
    try {
      const response = await apiClient.get('/signups/', { params })
      console.log('报名API响应:', response)
      return {
        items: response.items || response || [],
        total: response.total || (response?.length || 0),
        page: response.page || 1,
        page_size: response.page_size || 10,
        has_next: response.has_next || false,
        has_prev: response.has_prev || false
      }
    } catch (error) {
      console.error('获取报名列表失败:', error)
      return { items: [], total: 0 }
    }
  },

  async getSignup(id) {
    return await apiClient.get(`/signups/${id}`)
  },

  async createSignup(data) {
    return await apiClient.post('/signups', data)
  },

  async updateSignup(id, data) {
    return await apiClient.put(`/signups/${id}`, data)
  },

  async deleteSignup(id) {
    return await apiClient.delete(`/signups/${id}`)
  },

  async getSignupStats(id) {
    return await apiClient.get(`/signups/${id}/stats`)
  },

  // 报名记录相关接口
  async getEnrollments(params = {}) {
    try {
      const response = await apiClient.get('/signups/enrollments', { params })
      return {
        items: response.items || response || [],
        total: response.total || (response?.length || 0),
        page: response.page || 1,
        page_size: response.page_size || 10,
        has_next: response.has_next || false,
        has_prev: response.has_prev || false
      }
    } catch (error) {
      console.error('获取报名记录列表失败:', error)
      return { items: [], total: 0 }
    }
  },

  async getEnrollment(id) {
    return await apiClient.get(`/signups/enrollments/${id}`)
  },

  async createEnrollment(data) {
    return await apiClient.post('/signups/enrollments', data)
  },

  async cancelEnrollment(id) {
    return await apiClient.delete(`/signups/enrollments/${id}`)
  },

  async checkEnrollmentStatus(studentId, signupId) {
    return await apiClient.get(`/signups/enrollments/check/${studentId}/${signupId}`)
  }
}

// 培训机构API
export const agentAPI = {
  async getAgents(params = {}) {
    try {
      const response = await apiClient.get('/agents', { params })
      return {
        data: response.data || response || [],
        total: response.total || (response?.length || 0),
        page: response.page || 1,
        page_size: response.page_size || 20
      }
    } catch (error) {
      console.error('获取培训机构列表失败:', error)
      return { data: [], total: 0 }
    }
  },

  async getAgent(id) {
    return await apiClient.get(`/agents/${id}`)
  },

  async createAgent(data) {
    return await apiClient.post('/agents', data)
  },

  async updateAgent(id, data) {
    return await apiClient.put(`/agents/${id}`, data)
  },

  async deleteAgent(id) {
    return await apiClient.delete(`/agents/${id}`)
  },

  async approveAgent(id, isApproved) {
    return await apiClient.patch(`/agents/${id}/approval`, {
      is_approved: isApproved
    })
  },

  async getAgentStatistics() {
    try {
      const response = await apiClient.get('/agents/statistics/overview')
      return response || {}
    } catch (error) {
      console.error('获取培训机构统计信息失败:', error)
      return {}
    }
  },

  async checkCreditCode(creditCode) {
    return await apiClient.get(`/agents/check-credit-code/${creditCode}`)
  }
}

// 地区API
export const areaAPI = {
  async getAreas(params = {}) {
    try {
      const response = await apiClient.get('/areas', { params })
      return response || []
    } catch (error) {
      console.error('获取地区列表失败:', error)
      return []
    }
  },

  async getArea(id) {
    return await apiClient.get(`/areas/${id}`)
  }
}


// 新闻管理API
export const newsAPI = {
  async getNewsList(params = {}) {
    try {
      const response = await apiClient.get('/news/', { params })
      // 解析响应数据以获取总数和列表
      if (Array.isArray(response)) {
        // 如果响应是数组，总数就是数组长度
        return {
          items: response,
          total: response.length
        }
      } else if (response.items) {
        // 如果响应包含items字段
        return {
          items: response.items,
          total: response.total || response.items.length
        }
      } else {
        // 其他情况
        return {
          items: [],
          total: 0
        }
      }
    } catch (error) {
      console.error('获取新闻列表失败:', error)
      return { items: [], total: 0 }
    }
  },

  async getNews(id) {
    return await apiClient.get(`/news/${id}`)
  },

  async createNews(data) {
    return await apiClient.post('/news', data)
  },

  async updateNews(id, data) {
    return await apiClient.put(`/news/${id}`, data)
  },

  async deleteNews(id) {
    return await apiClient.delete(`/news/${id}`)
  }
}

//资源管理API
const resourceAPI = {
  async getResources(params = {}) {
    try {
      const response = await apiClient.get('/resources/', { params })
      return {
        items: response.items || response || [],
        total: response.total || (response?.length || 0)
      }
    } catch (error) {
      console.error('获取资源列表失败:', error)
      return { items: [], total: 0 }
    }
  },

  async getResource(id) {
    return await apiClient.get(`/resources/${id}`)
  },

  async createResource(data) {
    return await apiClient.post('/resources/', data)
  },

  async updateResource(id, data) {
    return await apiClient.put(`/resources/${id}`, data)
  },

  async deleteResource(id) {
    return await apiClient.delete(`/resources/${id}`)
  },
  
  async incrementDownloadCount(id) {
    return await apiClient.patch(`/resources/${id}/increment-download`)
  },
  
  async uploadFile(formData) {
    // 创建一个新的axios实例用于文件上传，不使用默认的Content-Type
    const uploadClient = axios.create({
      baseURL: API_BASE_URL,
      timeout: 30000
    })
    
    // 复用请求和响应拦截器的逻辑
    uploadClient.interceptors.request.use(
      config => {
        console.log('发送请求:', config.method?.toUpperCase(), config.url)
        const token = localStorage.getItem('token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      error => {
        console.error('请求错误:', error)
        return Promise.reject(error)
      }
    )
    
    uploadClient.interceptors.response.use(
      response => {
        console.log('收到响应:', response.status, response.config.url)
        return response.data
      },
      error => {
        console.error('响应错误:', error)
        if (error.code === 'ECONNREFUSED') {
          console.error('无法连接到服务器，请确保后端服务正在运行')
        }
        if (error.response?.status === 401) {
          localStorage.removeItem('token')
          window.location.href = '/login'
        }
        return Promise.reject(error)
      }
    )
    
    return await uploadClient.post('/resources/upload-file/', formData)
  },
  
  // 添加apiClient的引用，以便在组件中可以访问baseURL
  apiClient: apiClient
}

// 统一导出所有API
export const API = {
  student: studentAPI,
  teacher: teacherAPI,
  course: courseAPI,
  resource: resourceAPI,
  signup: signupAPI,
  agent: agentAPI,
  area: areaAPI,
  news: newsAPI,
  testConnection
}

// 默认导出
export default API